// pages/dashboard/index/index.js
import * as echarts from '../../../component/ec-canvas/echarts';
var chart1 = null
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    role:'',
    imageWidth: wx.getSystemInfoSync().windowWidth,//图片宽度   
    imgUrls: [],
    financialList: [],
    financialList_nh: [],
    scrollList: [],
    activeIndex:null,
    ec: {
      lazyLoad:true
    },
    date: '2020-10-10 至 2020-10-11',
    show: false,
    minDate: new Date(2021, 6, 1).getTime(),
    maxDate: new Date().getTime(),
    chartList: [],
    parsents:null,
		onLage:1,
		singleTime:''
  },
  onDisplay() {
    this.setData({ show: true });
  },
  onClose() {
    this.setData({ show: false });
  },
  formatDate(date) {
    date = new Date(date);
    var Y = date.getFullYear();
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    return `${Y}-${M}-${D}`;
  },
  onConfirm(event) {
    const [start, end] = event.detail;
    this.setData({
      show: false,
      date: `${this.formatDate(start)}至${this.formatDate(end)}`,
    });
		// debugger
		if(this.formatDate(end)===this.formatDate(start)){
			this.setData({
				onLage:2,
				singleTime:this.data.date.split('至')[0]
			})
		}else{
			this.setData({
				onLage:1
			})
		}
    this.getFinancial();
  },
  //获取banner
  getBanner() {
    let parmas = {
      // companyId: app.globalData.userInfo.companyData.companyId
			companyId:99999
    }
    wx.$apis.selectBannerList(parmas).then(res => {
      // wx.stopPullDownRefresh();
      if (res.data.records && res.data.records.length) {
        let newBanner = res.data.records.map(item => {
          return item.topicImage
        })
        this.setData({
          imgUrls: newBanner
        })
      }

    }).catch(err => {
      wx.hideLoading()
    })
  },
  //获取近7天时间---获取当天
  getSevenDay() {
    var timestamp = Date.parse(new Date());
    timestamp = timestamp / 1000;
    var date = new Date(timestamp * 1000);
    //获取年份
    var Y = date.getFullYear();
    //获取月份
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    //获取当日日期
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    //减7天的时间戳：
    var before_timetamp = timestamp - 24 * 60 * 60 * 6;
    //減7天的时间：
    var n_to = before_timetamp * 1000;
    var before_timetamp = new Date(n_to);
    var Y_before = before_timetamp.getFullYear();
    //月份
    var M_before = (before_timetamp.getMonth() + 1 < 10 ? '0' + (before_timetamp.getMonth() + 1) : before_timetamp.getMonth() + 1);
    //日期
    var D_before = before_timetamp.getDate() < 10 ? '0' + before_timetamp.getDate() : before_timetamp.getDate();
    // this.setData({
    //   date: `${Y_before}-${M_before}-${D_before}至${Y}-${M}-${D}`
    // })
		    this.setData({
					onLage:2,
					date: `${Y}-${M}-${D}至${Y}-${M}-${D}`,
					singleTime:`${Y}-${M}-${D}`,
    })
  },
  //财务状态
  getFinancial() {
		this.setData({
			financialList: [
				{ name: '卖菜收入（元）', count: 0, key: 'income' },
				{ name: '收菜支出（元）', count: 0, key: 'spend' },
				{ name: '盈利（元）', count: 0 ,key: 'profit' },
				{ name: '货主未打款（元）', count: 0, key: 'procurementNoInvoic' },
				{ name: '农户未打款（元）', count: 0, key: 'farmerNoInvoic' },
				{ name: '小工打款(元）', count: 0, key: 'coolieInvoic' },
			],
			financialList_nh:[
				{ name: '账本收入（元）', count: 0 , key: 'bookIncome'},
				{ name: '账本支出（元）', count: 0 , key: 'bookSpend'},
				{ name: '账本盈利（元）', count: 0 , key: 'boolProfit'},
				{ name: '代办未打款（元）', count: 0 , key: 'unInvoic'},
				{ name: '代办已打款（元）', count: 0 , key: 'invoic'},
			]
		})

    var parmas = {
      companyId: app.globalData.userInfo.companyData.companyId,
      startTime: this.data.date.split('至')[0] + " 00:00:00",
      endTime: this.data.date.split('至')[1] + " 23:59:59",
    }    
    let api;
		console.log(this.data.role,'this.data.role')
    if(this.data.role==1){
      api='marketCount'
    }else{
      api="farmerCount"

    }
    wx.$apis[api](parmas).then(res => {
      var data = res.data;
			if(this.data.role==1){
				var list = this.data.financialList.map(item => {
					return {
						name: item.name,
						count:wx.$getYuanUnit(data[item.key]),
						fen:wx.$getFenUnit(data[item.key])
					}
				});
				this.setData({
					financialList: list,
				})
			}else{
				var list = this.data.financialList_nh.map(item => {
					return {
						name: item.name,
						count:wx.$getYuanUnit(data[item.key]),
						fen:wx.$getFenUnit(data[item.key])
					}
				});
				this.setData({
					financialList: list,
				})
			}

    }).catch(err => {
      wx.hideLoading()
    })

  },
  //获取作物信息
  getCrops() {
    if(this.data.role ==1){
      let companyId = app.globalData.userInfo.companyData.companyId ;
      wx.$apis.marketCrops(companyId).then(res => {
				res.data.forEach(item=>{
					item.cropName=item.name
				})
        // wx.hideLoading()
        this.setData({
          scrollList: res.data,
          activeIndex: res.data[0].id,
        })
        console.log(this.data.activeIndex,'activeIndex')
        this.getCropChart()
  
      }).catch(err => {
        wx.hideLoading()
      })
    }else if (this.data.role ==2){
      //getFarmerCrops
      wx.$apis.getFarmerCrops().then(res => {
        var newArr=res.data.map(item => ({
          cropName: item.name,
          id: item.id
      }))
        // wx.hideLoading()
        this.setData({
          scrollList: newArr,
          activeIndex: newArr[0].id,
        })
        console.log(this.data.activeIndex,'activeIndex')
        this.getCropChart()
  
      }).catch(err => {
        wx.hideLoading()
      })
    }

  },
  scroll(e) {
  },
  handlescroll(e) {
    console.log(e)
    console.log(e.currentTarget.dataset.id)
    this.setData({
      activeIndex: e.currentTarget.dataset.id
    })
    this.getCropChart();
  },
  //获取echart
  getCropChart() {
    if(this.data.role==1){
      let companyId = app.globalData.userInfo.companyData.companyId * 1;
      let cropId = this.data.activeIndex;
      wx.$apis.daysCropChar(companyId, cropId).then(res => {
        let time = [];
        let salesWeight = [];//销售量
        let acquisitionWeight = []; //收购量
        let stockWeight = []; //库存量
        res.data.forEach(item => {
         let times= item.days.slice(5)
          time.push(times);
          acquisitionWeight.push(item.acquisitionWeight);
          salesWeight.push(item.salesWeight);
          stockWeight.push(item.stockWeight);
          let obj = {
            time,
            acquisitionWeight,
            salesWeight,
            stockWeight
          }
          this.setData({
            chartList: obj,
          })
        })
        // console.log(this.data.chartList, 'chart')
        // wx.hideLoading()
        this.init_echarts()
  
      }).catch(err => {
        wx.hideLoading()
      })
    }else{
      let cropId = this.data.activeIndex;
      wx.$apis.getCropChar(cropId).then(res => {
        let time = [];
        let acquisitionWeight = []; //收购量
        res.data.forEach(item => {
         let times= item.days.slice(5)
          time.push(times);
          acquisitionWeight.push(item.acquisitionWeight);
          let obj = {
            time,
            salesWeight:acquisitionWeight,
          }
          this.setData({
            chartList: obj,
          })
        })
        console.log(this.data.chartList, 'chart')
        wx.hideLoading()
        this.init_echarts()
  
      }).catch(err => {
        wx.hideLoading()
      })
    }


  },
  init_echarts: function () {
    this.echartsComponnet1.init((canvas, width, height, dpr) => {
     const chart1 = echarts.init(canvas, null, {
        width: width,
			 	height: height,
				devicePixelRatio: dpr
      });
      if(this.data.role==1){
        chart1.setOption(this.getOption());
      }else{
        chart1.setOption(this.getOption_nh());
      }
      return chart1;
    });
  },
  getOption: function () {
    var _this = this;
    var option = {
      smooth: true,
      tooltip: {
        trigger: 'axis'
      },
      color:["#8BB94F","#37B6FF","#FFB037"],
      center: ['50%', '40%'],
      legend: {
        top: "0%", // 组件离容器的距离
        bottom: "0%",
        right: "5%", // 组件离容器的距离
        data: ['销售量', '收购量', '库存量'],
      },
      grid: {
        left: '15%',
        right: '5%',
        // bottom: '20%',
        top: '20%',
      },
      tooltip:{
        trigger: 'axis',
        formatter:`{a0}:{c0}斤\n{a1}:{c1}斤\n{a2}:{c2}斤`
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: _this.data.chartList.time
      },
      yAxis: {
        type: 'value',
        name:'单位（斤）',
        scale:true,
        axisLine:{show:false},
        axisTick:{show:false},
        // min: 0,
        // max:1000,
        spiltNumber:7,
        splitLine: {
          //网格线
          lineStyle: {
            type: "dotted", //设置网格线类型 dotted：虚线 solid:实线
            width: 1,
          },
          show: true, //隐藏或显示
        },
      },
      series: [
        {
          name: '销售量',
          type: 'line',
          data: _this.data.chartList.salesWeight
        },
        {
          name: '收购量',
          type: 'line',
          data:_this.data.chartList.acquisitionWeight
        },
        {
          name: '库存量',
          type: 'line',
          data: _this.data.chartList.stockWeight
        },
      ]
    };
    return option;
  },
  getOption_nh: function () {
    var _this = this;
    var option = {
      smooth: true,
      tooltip: {
        trigger: 'axis'
      },
      color:["#8BB94F"],
      center: ['50%', '40%'],
      legend: {
        top: "0%", // 组件离容器的距离
        bottom: "0%",
        right: "5%", // 组件离容器的距离
        data: ['销售量'],
      },
      grid: {
        left: '15%',
        right: '5%',
        // bottom: '20%',
        top: '20%',
      },
      tooltip:{
        trigger: 'axis',
        formatter:`{a0}:{c0}斤`
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: _this.data.chartList.time
      },
      yAxis: {
        type: 'value',
        name:'单位（斤）',
        scale:true,
        axisLine:{show:false},
        axisTick:{show:false},
        // min: 0,
        // max:1000,
        spiltNumber:7,
        splitLine: {
          //网格线
          lineStyle: {
            type: "dotted", //设置网格线类型 dotted：虚线 solid:实线
            width: 1,
          },
          show: true, //隐藏或显示
        },
      },
      series: [
        {
          name: '销售量',
          type: 'line',
          data: _this.data.chartList.salesWeight
        },
      ]
    };
    return option;
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      role: app.globalData.userInfo.role,
    })
		if (this.data.role != 1) {
      this.setData({
        financialList: this.data.financialList_nh
      })

    }
    this.getBanner();
    this.getSevenDay();
    this.getFinancial();
    this.getCrops();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
 * 生命周期函数--监听页面显示
 */
  onShow: function () {
    this.echartsComponnet1 = this.selectComponent('#mychart1');
    this.init_echarts();
  },
  /**
 * 页面相关事件处理函数--监听用户下拉动作
 */
  onPullDownRefresh: function () {
		this.setData({
      role: app.globalData.userInfo.role,
    })
			this.getBanner();
			this.getSevenDay();
			this.getCrops();
			this.echartsComponnet1 = this.selectComponent('#mychart1');
			this.init_echarts();
			this.getFinancial();
			setTimeout(() => {
        wx.stopPullDownRefresh();
      }, 1000);

  },


});